"""
API场景组合测试工具 - 执行控制器
"""
from flask import Blueprint, request, jsonify, render_template
from app import db
from app.models.scene import Scene
from app.models.environment import Environment
from app.models.execution_record import ExecutionRecord
from app.models.step_execution_record import StepExecutionRecord
from ..services.execution_service import ExecutionService
import json
from datetime import datetime

exec_bp = Blueprint('execution', __name__, url_prefix='/execution')

@exec_bp.route('/', methods=['GET'])
def list_executions():
    """获取执行记录列表"""
    executions = ExecutionRecord.query.order_by(ExecutionRecord.start_time.desc()).all()
    exec_list = [exec.to_dict() for exec in executions]
    
    # 检查请求是否是AJAX请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return jsonify({'executions': exec_list})
    
    return render_template('execution/list.html', executions=exec_list)

@exec_bp.route('/<int:exec_id>', methods=['GET'])
def get_execution(exec_id):
    """获取单个执行记录详情"""
    execution = ExecutionRecord.query.get_or_404(exec_id)
    return render_template('execution/detail.html', execution=execution.to_dict())

@exec_bp.route('/', methods=['POST'])
def create_execution():
    """创建执行记录并开始执行"""
    data = request.json
    if not data:
        return jsonify({
            'success': False,
            'message': '无效的请求数据'
        }), 400
        
    scene_id = data.get('scene_id')
    environment_id = data.get('environment_id')
    template_data_id = data.get('template_data_id')
    template_env_id = data.get('template_env_id')
    
    # 验证场景和环境
    scene = Scene.query.get_or_404(scene_id)
    environment = Environment.query.get_or_404(environment_id)
    
    # 如果提供了模板环境ID，验证它
    if template_env_id:
        template_env = Environment.query.get_or_404(template_env_id)
    
    # 创建执行记录
    execution = ExecutionRecord(
        scene_id=scene_id,
        environment_id=environment_id,
        template_data_id=template_data_id,
        status='RUNNING'
    )
    
    db.session.add(execution)
    db.session.commit()
    
    # 异步执行场景
    try:
        # 创建执行服务
        execution_service = ExecutionService()
        
        # 开始执行
        execution_service.execute_scene_async(
            execution_id=execution.id,
            scene_id=scene_id,
            environment_id=environment_id,
            template_data_id=template_data_id,
            template_env_id=template_env_id
        )
        
        return jsonify({
            'success': True, 
            'message': '场景执行已开始', 
            'execution_id': execution.id
        })
    except Exception as e:
        # 更新执行记录状态为失败
        execution.status = 'FAILED'
        execution.end_time = datetime.now()
        execution.result = json.dumps({'error': str(e)})
        db.session.commit()
        
        return jsonify({
            'success': False, 
            'message': f'场景执行失败: {str(e)}', 
            'execution_id': execution.id
        })

@exec_bp.route('/<int:exec_id>/status', methods=['GET'])
def get_execution_status(exec_id):
    """获取执行状态"""
    execution = ExecutionRecord.query.get_or_404(exec_id)
    
    return jsonify({
        'execution_id': execution.id,
        'status': execution.status,
        'start_time': execution.start_time.strftime('%Y-%m-%d %H:%M:%S'),
        'end_time': execution.end_time.strftime('%Y-%m-%d %H:%M:%S') if execution.end_time else None,
        'scene_id': execution.scene_id,
        'environment_id': execution.environment_id,
        'template_data_id': execution.template_data_id
    })

@exec_bp.route('/<int:exec_id>/cancel', methods=['POST'])
def cancel_execution(exec_id):
    """取消执行"""
    execution = ExecutionRecord.query.get_or_404(exec_id)
    
    if execution.status == 'RUNNING':
        execution.status = 'CANCELLED'
        execution.end_time = datetime.now()
        execution.result = json.dumps({'message': '执行被用户取消'})
        db.session.commit()
        
        # 通知执行服务取消执行
        execution_service = ExecutionService()
        execution_service.cancel_execution(exec_id)
        
        return jsonify({'success': True, 'message': '执行已取消'})
    else:
        return jsonify({'success': False, 'message': '只能取消正在运行的执行'})

@exec_bp.route('/<int:exec_id>/steps', methods=['GET'])
def get_execution_steps(exec_id):
    """获取执行步骤记录"""
    steps = StepExecutionRecord.query.filter_by(execution_id=exec_id).order_by(StepExecutionRecord.start_time).all()
    return jsonify([step.to_dict() for step in steps])